/*
 * @Description: 聊天成员hook
 * @Author: xinqiao lxq1990.0716@qq.com
 * @Date: 2025-04-29
 * @LastEditors: xinqiao lxq1990.0716@qq.com
 * @LastEditTime: 2025-04-29
 */

import { computed, ref } from 'vue'

import type { IMChatMember } from '/@/components/im'
import { useIM } from '/@/components/im'

const { getChatMembers } = useIM()

export const useMember = (userId: string) => {
  /** 聊天成员 */
  const members = ref([] as IMChatMember[])

  /** 选中的聊天成员 */
  const checkedMember = computed(() => members.value.find((item) => item.checked === true))

  /** 选中的聊天成员id */
  const checkedMemberId = computed(() => {
    const { senderId, recipientId } = checkedMember.value as IMChatMember
    return senderId === userId ? recipientId : senderId
  })

  /**
   * 初始化聊天成员
   */
  const initMembers = async () => {
    const res = await getChatMembers()
    res.forEach((item, i) => addMember(item, i === 0))
  }

  /**
   * 添加聊天成员
   * @param checked 是否选中
   * @param member 聊天成员
   * @returns
   */
  const addMember = (member: ImMessagePageTypes.IResponse, checked: boolean) => members.value.push({ ...member, checked })

  /** 点击选中聊天成员 */
  const changeMember = (item: IMChatMember) => {
    ;(checkedMember.value as IMChatMember).checked = false
    item.checked = true
    onMemberChange()
  }

  /** 切换联调成员 */
  let onMemberChange

  /**
   * 设置聊天成员切换回调
   * @param fn 聊天成员切换回调
   * @returns
   */
  const setOnMemberChange = (fn: Function) => (onMemberChange = fn)

  /** 聊天成员搜索框值 */
  const searchMemberVal = ref('')

  /**
   * 搜索聊天成员
   * @param val 搜索值
   * @returns
   */
  const onSearchMember = (val: string) => console.log('useMember.onSearch: ', val)

  return {
    members,
    checkedMember,
    checkedMemberId,
    initMembers,
    addMember,
    changeMember,
    setOnMemberChange,
    searchMemberVal,
    onSearchMember,
  }
}

export default useMember
